package com.example.demo.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.example.demo.entity.Result;
import com.example.demo.mapper.FinanceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FinanceServiceImpl {
    @Autowired
    private FinanceMapper financeMapper;
    @Value("${download.path}")
    private String filePaths;
    public Result getAllFinance(Map<String, Object> params) {
        Integer pageIndex=Integer.parseInt(params.get("pageIndex").toString())-1;
        Integer pageSize=Integer.parseInt(params.get("pageSize").toString());
        params.put("pageIndex",pageIndex*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String,Object>> list=financeMapper.getAllFinance(params);
        //收款率
        if(list!=null&&list.size()>0){
            list.stream()
                    .forEach(it->{
                        if(Objects.nonNull(it.get("receivables"))&&Objects.nonNull(it.get("amountReceived"))){
                            it.put("collRate",Double.parseDouble(it.get("amountReceived").toString())/Double.parseDouble(it.get("receivables").toString()));
                        }
                    });
        }
        int count=financeMapper.getCont();
        return Result.ok(list).setRecordsCount((long) count);
    }

    @Transactional
    public Result insertFinance(Map<String, Object> params) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String pk_id= UUID.randomUUID().toString();
        params.put("pkId",pk_id.substring(0,5));
        Map<String,Object> map=new HashMap<>();
        map.put("pkId",UUID.randomUUID().toString().substring(0,7));
        map.put("projectId",params.get("projectId"));
        map.put("expenseId",params.get("pkId"));
        financeMapper.insertProFin(map);
        params.put("crtDt",sdf.format(new Date()));
        financeMapper.insertFinance(params);
        return  Result.OK_EMPTY;
    }
    @Transactional
    public Result updateFinance(Map<String, Object> params) {
        financeMapper.updateFinance(params);
        return  Result.ok("维护报表成功");
    }

    public Result deleteFinance(Map<String, Object> params) {
        financeMapper.deleteFinance(params);
        return Result.OK_EMPTY;
    }

    public Result getMonthFinance(Map<String, Object> params) {
        List<Map<String,Object>> list=financeMapper.getMonthFinance(params);
        List<String> xAxis=null;
        List<String> receivables=null;
        List<String> amountReceived=null;
        if(list!=null&&list.size()>0){
             xAxis = list.stream().map(it -> it.get("month").toString()).collect(Collectors.toList());
            receivables = list.stream().map(it -> it.get("sumreceivables").toString()).collect(Collectors.toList());
            amountReceived = list.stream().map(it -> it.get("sumamountReceived").toString()).collect(Collectors.toList());
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("xAxis",xAxis);
        map.put("receivables",receivables);
        map.put("amountReceived",amountReceived);
        return Result.ok(map);
    }

    public Result getMonthFinance1(Map<String, Object> params) {
        List<Map<String,Object>> list=financeMapper.getMonthFinance1(params);
        List<String> xAxis=null;
        List<String> lineData=null;
        if(list!=null&&list.size()>0){
            xAxis = list.stream().map(it -> it.get("month").toString()).collect(Collectors.toList());
            lineData = list.stream().map(it -> it.get("lineData").toString()).collect(Collectors.toList());
        }
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("xAxis",xAxis);
        map.put("lineData",lineData);
        return Result.ok(map);
    }

    public Result getExpense(Map<String, Object> params) {
        Integer pageIndex=Integer.parseInt(params.get("pageIndex").toString())-1;
        Integer pageSize=Integer.parseInt(params.get("pageSize").toString());
        params.put("pageIndex",pageIndex*pageSize);
        params.put("pageSize",pageSize);
        List<Map<String,Object>> list=financeMapper.getExpense(params);
        int count=financeMapper.getExpenseCont();
        return Result.ok(list).setRecordsCount((long) count);
    }

    public Result insertExpense(MultipartFile[] file, Map<String, Object> map, HttpServletRequest request) {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Map<String,Object> paramMap= (Map<String, Object>) JSONUtils.parse(map.get("paramMap").toString());
        //返回图片保存地址
        String img=null;
        if(file!=null&&file.length>0){
            img= file[0].getOriginalFilename();
        }
        storeFile(file, filePaths,request);
        paramMap.put("pkId",UUID.randomUUID().toString().substring(0,7));
        paramMap.put("bill",img);
        paramMap.put("crtDt",sdf.format(new Date()));
        financeMapper.insertExpense(paramMap);
        return Result.ok("新增报销成功");
    }
    //存储File
    public String storeFile(MultipartFile[] files, String path,HttpServletRequest request) {
        List<String> paths=new ArrayList<>();
        if(!Objects.isNull(files)){
            for (MultipartFile file:files) {
                // 获取原始文件名
                String fileName = file.getOriginalFilename();
                // // 获取文件后缀
                // String suffixName = fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".")) : null;
                // //文件的保存重新按照时间戳命名
                // String newFileName = System.currentTimeMillis() + suffixName;
                // 最终保存的文件
                File filePath = new File(path + File.separator + fileName);
                // 判断文件夹是否存在
                if (!filePath.getParentFile().exists()) {
                    filePath.getParentFile().mkdirs();
                }
                // 保存文件
                try {
                    file.transferTo(filePath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                paths.add(filePath.toString());
                // 如果成功，会返回文件的绝对路径，方便下载
            }
        }
        String uploadPath=null;
        if(paths.size()>0){
            uploadPath= String.join(",", paths);
        }
        return uploadPath;
    }

    @Transactional
    public Result deleteExpense(Map<String, Object> paramMap, HttpServletRequest request) {
        financeMapper.deleteExpense(paramMap);
        return Result.OK_EMPTY;
    }
}
